$(function() {

  var siteUrl = location.href.split('#')[1];
  if (!siteUrl) return;
  siteUrl = decodeURIComponent(siteUrl);
  var request;
  try { request = JSON.parse(window.name); } catch(e) {}
  if (request && request.token) {
    doOAuthRequest();
  } else {
    bindSite(siteUrl, returnToken);
  }

  function bindSite(siteUrl, callback) {
    $.ajax({
      url : '/oauth/bind',
      data : { site_url : siteUrl },
      dataType : 'json',
      success : function(res) { callback(siteUrl, res.token); }
    });
  }

  function returnToken(siteUrl, token) {
    location.href = siteUrl + '#' + encodeURIComponent(token);
  }

  function doOAuthRequest() {
    $.ajax({
      url : '/oauth/proxy',
      data : request,
      success : handleSuccess,
      error : handleError
    });
  }

  function handleSuccess(data, status) {
    doOAuthResponse(status=="success" ? 200 : 500, data);
  }

  function handleError(xhr) {
    if (xhr.status==401) {
      handleOAuthAuthorize();
    } else {
      doOAuthResponse(xhr.status, xhr.responseText);
    }
  }

  var oauthPrompted = false;
  function handleOAuthAuthorize() {
    if (oauthPrompted) {
      doOAuthResponse(401, "Unauthorized");
      return;
    }
    oauthPrompted = true;
    var w = window.open(
      '/oauth/authorize?request_url='+encodeURIComponent(request.url)+
      '&site_token='+request.token, null,
      'width=600,height=400,menubar=no,location=yes,toolbar=no,scrollbars=yes');
    if (!w) {
      doOAuthResponse(500, "Please disable popup blocker");
      return;
    }
    var PID = window.setInterval(checkAuthorized, 100);
    function checkAuthorized() {
      if (w.closed) {
        window.clearInterval(PID);
        doOAuthRequest();
      }
    }
  }

  function doOAuthResponse(status, body) {
    window.name = JSON.stringify({ status : status, body : body });
    location.href = siteUrl;
  }

})
